package com.pet.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.article.feign.ApBehaviorEntryFeign;
import com.pet.article.mapper.ApArticleMapper;
import com.pet.article.mapper.ApCollectionMapper;
import com.pet.article.service.ApCollectionService;
import com.pet.common.constants.MQConstants;
import com.pet.common.exception.LeadNewsException;
import com.pet.model.article.pojos.ApArticle;
import com.pet.model.article.pojos.ApCollection;
import com.pet.model.article.pojos.ApCollectionDto;
import com.pet.model.behavior.dtos.UpdateArticleMsg;
import com.pet.model.behavior.pojos.ApBehaviorEntry;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.user.pojos.ApUser;
import com.pet.utils.common.JsonUtils;
import com.pet.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;


/**
 * <p>
 * APP收藏信息表 服务实现类
 * </p>
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    private ApBehaviorEntryFeign apBehaviorEntryFeign;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ApCollection getApCollection(Integer entryId, Long articleId) {
        QueryWrapper<ApCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("entry_id",entryId);
        queryWrapper.eq("article_id",articleId);
        return getOne(queryWrapper);
    }

    @Override
    public ResponseResult collectionBehavior(ApCollectionDto dto) {
        //1.取出登录用户信息
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        Integer userId = null;
        if(apUser!=null){
            userId = apUser.getId();
        }
        //2.取出设备信息
        Integer equipmentId = dto.getEquipmentId();
        //3.查询行为实体
        ApBehaviorEntry behaviorEntry = apBehaviorEntryFeign.findByUserIdOrEquipmentId(userId, equipmentId);
        if(behaviorEntry==null){
            throw new LeadNewsException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        try {
            //4.查询收藏记录是否存在
            QueryWrapper<ApCollection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("entry_id",behaviorEntry.getId());
            queryWrapper.eq("article_id",dto.getEntryId());
            ApCollection apCollection = getOne(queryWrapper);
            //根据文章id查询文章
            QueryWrapper<ApArticle> apArticleQueryWrapper = new QueryWrapper<>();
            apArticleQueryWrapper.eq("id",dto.getEntryId());
            ApArticle apArticle = apArticleMapper.selectOne(apArticleQueryWrapper);
            //4.1 不存在，添加收藏记录
            if(apCollection==null&&dto.getOperation().equals(0)){
                apCollection = new ApCollection();
                apCollection.setEntryId(behaviorEntry.getId());
                apCollection.setArticleId(dto.getEntryId());
                apCollection.setType(dto.getType());
                apCollection.setCollectionTime(new Date());
                apCollection.setPublishedTime(apArticle.getPublishTime());
                save(apCollection);
            }else {
                remove(queryWrapper);
            }

            //收藏行为时发送MQ消息
            if(dto.getOperation().equals(0)){
                UpdateArticleMsg updateArticleMsg = new UpdateArticleMsg();
                updateArticleMsg.setType(UpdateArticleMsg.UpdateArticleType.COLLECTION);
                updateArticleMsg.setArticleId(dto.getEntryId());

                kafkaTemplate.send(MQConstants.HOT_ARTICLE_INPUT_TOPIC, UUID.randomUUID().toString(), JsonUtils.toString(updateArticleMsg));
            }

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
